package com.example.a2022application.storage;


import android.content.Context;
import android.util.Log;

import com.example.a2022application.bean.ClassEntity;
import com.example.a2022application.utils.SpUtils;
import com.example.a2022application.utils.SpUtils2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class CourseStorage implements ISharedPreferencesStorage<Integer, List<ClassEntity>> {
    private SpUtils2 mSpUtils =SpUtils2.getInstance();

    @Override
    public String setValue(Integer key, List<ClassEntity> value) {
        try {
            JSONArray array =new JSONArray();
            for (int i = 0; i < value.size(); i++) {
                ClassEntity classEntity = value.get(i);
                JSONObject object =new JSONObject();
                object.put("start",classEntity.getStartNode());
                object.put("end",classEntity.getEndNode());
                object.put("class_name",classEntity.getClassNamae());
                object.put("course_name",classEntity.getCourseName());
                object.put("time",classEntity.getTime());
                object.put("week",classEntity.getWeek());
                object.put("obj_id",classEntity.getObj_id());
                array.put(object);
            }
            mSpUtils.setString("class_info_" + key,array.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    public List<ClassEntity> getValue(Integer key, List<ClassEntity> defValue) {
        try {
            JSONArray weekJson;
            String week = SpUtils2.getInstance().getString("class_info_" + key);
            if (week.length()==0){
                return defValue;
            }
            List<ClassEntity> result =new ArrayList<>();
            weekJson =new JSONArray(week);
            for (int i = 0; i < weekJson.length(); i++) {
                JSONObject jsonObject = weekJson.getJSONObject(i);
                ClassEntity entity = new ClassEntity(
                        jsonObject.getInt("start"),
                        jsonObject.getInt("end"),
                        jsonObject.optString("class_name"),
                        jsonObject.optString("course_name"),
                        jsonObject.optString("obj_id"));
                entity.setTime(jsonObject.optString("time"));
                entity.setWeek(jsonObject.optString("week"));
                entity.setState(1);
                result.add(entity);
            }
            return  result;

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return defValue;
    }

    public void clear(){
        SpUtils2.getInstance().clear();
    }
}
